package xhwl.insurance.adapter;

import android.content.Context;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lidroid.xutils.util.LogUtils;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.R;
import xhwl.insurance.customView.CircleImageView;
import xhwl.insurance.event.SendVoiceEvent;
import xhwl.insurance.http.bean.RecordItem;
import xhwl.insurance.http.bean.resp.CustomerServiceLeftResp;
import xhwl.insurance.http.bean.resp.StaffServiceListResp;
import xhwl.insurance.util.ImgTools;
import xhwl.insurance.view.CustomShapeTransformation;

import static android.R.attr.duration;

/**
 * Created by fuyi on 2017/11/1.
 */

public class StaffServiceAdapter extends RecyclerView.Adapter {
    public Context context;

    private OnItemClickLitener onItemClickLitener;
    private List<StaffServiceListResp> mlist;
    public static final int LEFT_RECEIVE_MESSAGE = 1;//接收消息类型
    public static final int RIGHT_SEND_MESSAGE = 0;//发送消息类型
    private int min_length;
    private int max_length;
    private MediaPlayer mediaPlayer;


    public StaffServiceAdapter(Context context, List<StaffServiceListResp> mlist) {
        this.context = context;
        this.mlist = mlist;

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        min_length = (int) (metrics.widthPixels * 0.1f);
        max_length = (int) (metrics.widthPixels * 0.8f);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        RecyclerView.ViewHolder holder = null;
        switch (viewType) {
            case RIGHT_SEND_MESSAGE://发送消息类型
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_sendvoicemessage, null);
                holder = new SendMessageViewHolder(view);
                break;
            case LEFT_RECEIVE_MESSAGE://接收消息类型
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_rservice1message, null);
                holder = new ReceiveMessageHolder(view);
                break;
        }
        return holder;
    }


    public int getItemViewType(int position) {
        String id = mlist.get(position).getUSER_ID();
        if (id.equals("0")) {
            return RIGHT_SEND_MESSAGE;
        } else {
            return LEFT_RECEIVE_MESSAGE;
        }

    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        int itemViewType = getItemViewType(position);
        mediaPlayer = new MediaPlayer();
        switch (itemViewType) {
            case RIGHT_SEND_MESSAGE://发送消息类型
                setSendUserLayout((SendMessageViewHolder) holder, position);
                break;

            case LEFT_RECEIVE_MESSAGE://接收消息类型
                setReceiveUserLayout((ReceiveMessageHolder) holder, position);
                break;
        }

    }

    @Override
    public int getItemCount() {
        return mlist.size();
    }

    private void setReceiveUserLayout(final ReceiveMessageHolder holder, final int position) {
        if (mlist.get(position).getTALK_TYPE().equals("voice")) {
            holder.voice_rervice_voice_layout.setVisibility(View.VISIBLE);
            holder.voice_display_voice_time.setVisibility(View.VISIBLE);
            holder.ll_rervice_text.setVisibility(View.GONE);
            holder.ll_rervice_image.setVisibility(View.GONE);


            /**
             * 根据url获取时长
             */
            String url = mlist.get(position).getVOICE_FORMAT();
            try {

                mediaPlayer.setDataSource(url);
                mediaPlayer.prepare();
                int duration = mediaPlayer.getDuration();
                float duration2 = (float) duration / 1000;
                String time = String.valueOf(duration2);
                int time2 = Integer.parseInt(time.substring(0, time.lastIndexOf(".")));

                char c = time.substring(time.lastIndexOf(".")).charAt(1);
                if (c >= 0 && c < 5) {
                    holder.voice_display_voice_time.setText(Integer.toString(time2) + " ''");
                } else {
                    time2 += 1;
                    holder.voice_display_voice_time.setText(Integer.toString(time2) + " ''");
                }

            } catch (IOException e) {

                e.printStackTrace();
            }

        } else if (mlist.get(position).getTALK_TYPE().equals("image")) {
            holder.voice_rervice_voice_layout.setVisibility(View.GONE);
            holder.ll_rervice_text.setVisibility(View.GONE);
            holder.ll_rervice_image.setVisibility(View.VISIBLE);
            holder.voice_display_voice_time.setVisibility(View.GONE);

            Glide.with(context).load(mlist.get(position).getIMAGE_PICURL())
                    .transform(new CustomShapeTransformation(context, R.drawable.kefuchatbg))
                    .into(holder.iv_rervicechat_image);

        } else if (mlist.get(position).getTALK_TYPE().equals("text")) {
            holder.content.setText(mlist.get(position).getTALK_CONTENT());
            holder.voice_rervice_voice_layout.setVisibility(View.GONE);
            holder.ll_rervice_text.setVisibility(View.VISIBLE);
            holder.ll_rervice_image.setVisibility(View.GONE);
            holder.voice_display_voice_time.setVisibility(View.GONE);
        } else {

        }


        if (onItemClickLitener != null) {
            holder.fl_animeView_rervice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    EventBus.getDefault().post(new SendVoiceEvent());
                    onItemClickLitener.onReceiveVoiceItemClick(position, holder.itemView);

                }
            });
            holder.iv_rervicechat_image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onItemClickLitener.onReceivePictureDetailsClick(position, holder.iv_rervicechat_image);
                }
            });
        }
    }

    private void setSendUserLayout(final SendMessageViewHolder mSendVoiceHolder, final int position) {
        if (mlist.get(position).getTALK_TYPE().equals("voice")) {
            mSendVoiceHolder.rl_sendtvideo.setVisibility(View.VISIBLE);
            mSendVoiceHolder.rl_sendtext.setVisibility(View.GONE);
            mSendVoiceHolder.rl_sendimage.setVisibility(View.GONE);
            mSendVoiceHolder.time.setVisibility(View.VISIBLE);

            /**
             * 根据url获取时长
             */
            String url = mlist.get(position).getVOICE_FORMAT();
            try {
                mediaPlayer.setDataSource(url);
                mediaPlayer.prepare();
                int duration = mediaPlayer.getDuration();
                float duration2 = (float) duration / 1000;
                String time = String.valueOf(duration2);
                int time2 = Integer.parseInt(time.substring(0, time.lastIndexOf(".")));
                char c = time.substring(time.lastIndexOf(".")).charAt(1);

                if (c >= 0 && c < 5) {
                    mSendVoiceHolder.time.setText(Integer.toString(time2) + "'' ");
                } else {
                    time2 += 1;
                    mSendVoiceHolder.time.setText(Integer.toString(time2) + "'' ");
                }

            } catch (IOException e) {
                e.printStackTrace();
            }


        } else if (mlist.get(position).getTALK_TYPE().equals("image")) {
            mSendVoiceHolder.rl_sendtvideo.setVisibility(View.GONE);
            mSendVoiceHolder.rl_sendtext.setVisibility(View.GONE);
            mSendVoiceHolder.rl_sendimage.setVisibility(View.VISIBLE);
            mSendVoiceHolder.time.setVisibility(View.GONE);

        } else if (mlist.get(position).getTALK_TYPE().equals("text")) {
            mSendVoiceHolder.rl_sendtvideo.setVisibility(View.GONE);
            mSendVoiceHolder.rl_sendtext.setVisibility(View.VISIBLE);
            mSendVoiceHolder.rl_sendimage.setVisibility(View.GONE);
            mSendVoiceHolder.time.setVisibility(View.GONE);
            mSendVoiceHolder.tv_sendtext.setText(mlist.get(position).getTALK_CONTENT());
        } else {

        }

        String MEMBER_PIC = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_PIC, "");
        Glide.with(context).load(MEMBER_PIC).error(R.drawable.xiaoren).into(mSendVoiceHolder.iv_sendhead);

        Glide.with(context).load(mlist.get(position).getIMAGE_PICURL())
                .transform(new CustomShapeTransformation(context, R.drawable.userchatbg))
                .error(R.drawable.icon_fail)
                .into(mSendVoiceHolder.iv_sendimage);


        if (onItemClickLitener != null) {
            mSendVoiceHolder.fl_animeView_send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    EventBus.getDefault().post(new SendVoiceEvent());
                    onItemClickLitener.onSendVoiceItemClick(position, mSendVoiceHolder.itemView);

                }
            });
            mSendVoiceHolder.iv_sendimage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onItemClickLitener.onSendPictureDetailsClick(position, mSendVoiceHolder.iv_sendimage);
                }
            });
        }
    }

    class ReceiveMessageHolder extends RecyclerView.ViewHolder {
        private TextView content;
        private FrameLayout ll_rervice_text;
        private RelativeLayout voice_rervice_voice_layout;
        private FrameLayout ll_rervice_image;
        private ImageView iv_rervicechat_image;
        private FrameLayout fl_animeView_rervice;
        private View v_anime_rervice;
        private TextView voice_display_voice_time;

        public ReceiveMessageHolder(View itemView) {
            super(itemView);
            ll_rervice_text = (FrameLayout) itemView.findViewById(R.id.fl_rervice_text);
            voice_rervice_voice_layout = (RelativeLayout) itemView.findViewById(R.id.voice_rervice_voice_layout);
            ll_rervice_image = (FrameLayout) itemView.findViewById(R.id.ll_rervice_image);
            content = (TextView) itemView.findViewById(R.id.tv_chat);
            iv_rervicechat_image = (ImageView) itemView.findViewById(R.id.iv_rervicechat_image);
            v_anime_rervice = (View) itemView.findViewById(R.id.v_anime_rervice);
            fl_animeView_rervice = (FrameLayout) itemView.findViewById(R.id.voice_display_voice_play);
            voice_display_voice_time = (TextView) itemView.findViewById(R.id.voice_display_voice_time);
        }
    }

    public class SendMessageViewHolder extends RecyclerView.ViewHolder {

        private View animeView;
        private FrameLayout fl_animeView_send;
        private TextView time;
        private TextView tv_sendtext;
        private ImageView iv_sendhead;
        private RelativeLayout rl_sendtvideo;
        private RelativeLayout rl_sendtext;
        private RelativeLayout rl_sendimage;
        private ImageView iv_sendimage;

        public SendMessageViewHolder(View itemView) {
            super(itemView);
            iv_sendhead = (ImageView) itemView.findViewById(R.id.iv_sendhead);
            rl_sendtvideo = (RelativeLayout) itemView.findViewById(R.id.rl_sendtvideo);
            rl_sendtext = (RelativeLayout) itemView.findViewById(R.id.rl_sendtext);
            rl_sendimage = (RelativeLayout) itemView.findViewById(R.id.rl_sendimage);

            animeView = (View) itemView.findViewById(R.id.v_animes);
            fl_animeView_send = (FrameLayout) itemView.findViewById(R.id.fls);
            time = (TextView) itemView.findViewById(R.id.tv_times);
            tv_sendtext = (TextView) itemView.findViewById(R.id.tv_sendtext);
            iv_sendimage = (ImageView) itemView.findViewById(R.id.iv_sendimage);

        }
    }


    public interface OnItemClickLitener {
        void onSendVoiceItemClick(int position, View view);

        void onReceiveVoiceItemClick(int position, View view);

        void onSendPictureDetailsClick(int position, View view);

        void onReceivePictureDetailsClick(int position, View view);

    }

    public void setOnItemClickLitener(OnItemClickLitener onItemClickLitener) {
        this.onItemClickLitener = onItemClickLitener;
    }
}
